package com.mayn.action;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayn.common.JfinalInit;
import com.mayn.util.DriverFactory;
import com.mayn.util.HttpUtil;
import com.mayn.util.ProcessUtil;
import com.mayn.util.WebDriverUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CancelCainiaoOrder {

	private static final Logger LOG = LoggerFactory.getLogger(CancelCainiaoOrder.class);

	static String loginUrl = "https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fwork.cainiao.com%2F";
	static String userName = "宁美国度官方旗舰店:大刀";
	static String userPass = "ningmei=123";

	static String cookie = "";

	public static void main(String[] args) {

		// 需要用到聚石塔服务器数据库
		JfinalInit.InitDb(false,null);

		// 登录获取cookie
		cookie = getTaobaoLoginCookieStr();
		LOG.info(cookie);

		// 业务处理
		int start = 0;
		int limit = 100;
		
		
		deal(start, limit, 5);
		deal(start, limit, 4);
		deal(start, limit, 1);

	}

	public static void deal(int start, int limit, int status) {
		int totalCount = 0;
		int totalPage = 0;
		String errorOrderString = getErrorOrder(cookie, start, limit, status);
		JSONObject errorOrderJson = JSONObject.fromObject(errorOrderString);
		// 取总数量和页数
		if (errorOrderJson.containsKey("success") && errorOrderJson.getString("success").equals("true")) {
			if (errorOrderJson.containsKey("total")) {
				totalCount = errorOrderJson.getInt("total");
				LOG.info("共有" + String.valueOf(totalCount) + "条问题订单需要处理");
			}
		}
		if (totalCount > 0) {
			if (errorOrderJson.containsKey("pagination")) {
				totalPage = errorOrderJson.getJSONObject("pagination").getInt("totalPage");
			}
			// 先处理第一页
			JSONArray data = errorOrderJson.getJSONArray("data");
			dealOrderList(data);
			// 循环从第二页开始处理
			for (int j = 2; j <= totalPage; j++) {
				start = (j-1) * limit;
				errorOrderString = getErrorOrder(cookie, start, limit, status);
				errorOrderJson = JSONObject.fromObject(errorOrderString);
				data = errorOrderJson.getJSONArray("data");
				dealOrderList(data);
			}
		} else {
			LOG.error("错误：" + errorOrderString);
		}
	}

	/**
	 * 处理每页订单列表
	 * 
	 * @return
	 */
	public static void dealOrderList(JSONArray data) {
		if (data.size() > 0) {
			for (int i = 0; i < data.size(); i++) {
				String orderCode = data.getJSONObject(i).getString("orderCode");
				String tradeId = data.getJSONObject(i).getString("tradeId");
				String status = JdpTbTradeAction.getWebStatus(5, tradeId);
				if (status.equals("TRADE_FINISHED") || status.equals("TRADE_CLOSED") || status.equals("WAIT_BUYER_CONFIRM_GOODS")) {
					if (cancelErrorOrder(cookie, orderCode)) {
						LOG.info("订单--" + tradeId + "--" + status + "--取消成功");
					}
				} else {
					LOG.info("订单--" + tradeId + "--" + status + "--不能取消");
				}
			}
		}
	}

	/**
	 * 问题订单取消
	 */
	public static boolean cancelErrorOrder(String cookie, String orderCode) {

		String url = "http://core.work.cainiao.com/order/CancelOrder.do";

		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
		headers.put("Accept-Encoding", "gzip,deflate");
		headers.put("Host", "core.work.cainiao.com");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie", "cna=FrmhEMVAZBECAT23zfVaG67p; t=11589461494bf939d247dfe4188cb9a4; _tb_token_=2C1KDi4efPC5; cookie2=e741f3ca47a06f790d256b24f5e08b91; uss=Ane9lGrr0hpjjRyri5n5aPY6uXWI4HURPmMs1LID8J9Cp%2F11NanlLM1h3Mo%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; unb=2965098721; skt=1c6c6c0bbf8561b0; l=AoaGRYJFKhmTctireid6yUptVnYH/8pD; isg=Av__pZ9Wm2aj5p9gkkOlKk40jtOYReHlG2aNQpHDg64XoAwipbdv1-L2lMek");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("Connection", "keep-alive");
		headers.put("Content-Type", "application/x-www-form-urlencoded");

		JSONObject json = new JSONObject();
		json.put("reasons", "商家仓发货订单");
		json.put("otherReason", "商家仓发货订单");
		json.put("codes", orderCode);

		LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		// 参数传递，问题订单
		params.put("data", json.toString());
		String resp = "";
		resp = HttpUtil.sendPostWithURLConnection(url, params, headers);

		JSONObject returnMsg = JSONObject.fromObject(resp.trim());
		if (returnMsg.containsKey("success") && returnMsg.getString("success").equals("true")) {
			return true;
		} else {
			LOG.error("订单取消失败--" + orderCode + "--" + returnMsg.getString("errorMessage"));
			return false;
		}

	}

	/**
	 * 问题订单抓取 问题订单1,缺货订单4,待客服处理5
	 */
	public static String getErrorOrder(String cookie, int start, int limit, int status) {

		String url = "http://core.work.cainiao.com/order/QueryOrder.do";

		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/javascript, */*; q=0.01");
		headers.put("Accept-Encoding", "gzip,deflate");
		headers.put("Host", "core.work.cainiao.com");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36");
		if (cookie == null || cookie.trim().equals("")) {
			headers.put("Cookie", "cna=FrmhEMVAZBECAT23zfVaG67p; t=11589461494bf939d247dfe4188cb9a4; _tb_token_=2C1KDi4efPC5; cookie2=e741f3ca47a06f790d256b24f5e08b91; uss=Ane9lGrr0hpjjRyri5n5aPY6uXWI4HURPmMs1LID8J9Cp%2F11NanlLM1h3Mo%3D; tracknick=; sn=%E5%AE%81%E7%BE%8E%E5%9B%BD%E5%BA%A6%E5%AE%98%E6%96%B9%E6%97%97%E8%88%B0%E5%BA%97%3A%E5%A4%A7%E5%88%80; unb=2965098721; skt=1c6c6c0bbf8561b0; l=AoaGRYJFKhmTctireid6yUptVnYH/8pD; isg=Av__pZ9Wm2aj5p9gkkOlKk40jtOYReHlG2aNQpHDg64XoAwipbdv1-L2lMek");
		} else {
			headers.put("Cookie", cookie);
		}
		headers.put("Connection", "keep-alive");
		headers.put("Content-Type", "application/x-www-form-urlencoded");

		JSONObject json = new JSONObject();
		json.put("queryCode", "");
		json.put("shopId", "");
		json.put("buyerNick", "");
		json.put("goodsNo", "");
		json.put("warehouseCode", "");
		json.put("bizStatus", status);// 问题订单1,缺货订单4,待客服处理5

		LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		// 参数传递，问题订单
		params.put("data", json.toString());
		params.put("start", String.valueOf(start));
		params.put("limit", String.valueOf(limit));

		String resp = "";

		resp = HttpUtil.sendPostWithURLConnection(url, params, headers);

		return resp.trim();

	}

	/**
	 * 登录获取cookie
	 * 
	 * @return
	 */
	public static String getTaobaoLoginCookieStr() {
		String cookieStr = "";
		Set<Cookie> cookieSet = getTaobaoLoginCookie();
		if (cookieSet == null) {
			return cookieStr;
		} else {
			for (Cookie ck : cookieSet) {
				cookieStr = cookieStr + ";" + ck.getName() + "=" + ck.getValue();
			}
			if (cookieStr.startsWith(";")) {
				cookieStr = cookieStr.substring(1, cookieStr.length());
			}
		}
		return cookieStr;
	}

	/**
	 * 登录获取cookie
	 * 
	 * @return
	 */
	public static Set<Cookie> getTaobaoLoginCookie() {
		Set<Cookie> cookieSet = null;
		WebDriver driver = null;
		try {
			driver = DriverFactory.getWebDriver();
			driver.get(loginUrl);
			By by = null;
			WebElement loginBox = driver.findElement(By.id("J_LoginBox"));
			if (loginBox != null) {
				if (!loginBox.getAttribute("class").contains("module-static")) {
					WebElement J_Quick2Static = driver.findElement(By.id("J_Quick2Static"));
					if (J_Quick2Static != null) {
						WebDriverUtil.waitUntilVisible(driver, J_Quick2Static);
						J_Quick2Static.click();
					}
				}
			}

			ProcessUtil.ThreadSleep(1024);
			by = By.xpath("//input[@name='TPL_username']");
			WebElement user = driver.findElement(by);
			if (user != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				user.clear();
				user.sendKeys(userName);
			}

			ProcessUtil.ThreadSleep(800);
			by = By.xpath("//input[@name='TPL_password']");
			WebElement password = driver.findElement(by);
			if (password != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
				password.clear();
				password.sendKeys(userPass);
			}

			ProcessUtil.ThreadSleep(200);
			by = By.id("J_SubmitStatic");
			WebElement submit = driver.findElement(by);
			if (submit != null) {
				WebDriverUtil.moveToElementAndClick(driver, by);
			}
			ProcessUtil.ThreadSleep(500);
			LOG.debug(driver.getCurrentUrl());
			int sleepMs = 0;
			while (true) {
				if (driver.getCurrentUrl().startsWith("http://work.taobao.com")) {
					break;
				}
				if (driver.getCurrentUrl().startsWith("https://mai.taobao.com")) {
					driver.get("http://base.work.cainiao.com/manage/goods/item/itemManage.htm");
					if (driver.getCurrentUrl().startsWith("http://base.work.cainiao.com")) {
						break;
					}
				}
				sleepMs += 1000;
				LOG.info("还未登录成功,等待1000ms --" + driver.getCurrentUrl());
				ProcessUtil.ThreadSleep(1000);
				if (sleepMs >= 60000) {
					LOG.info("还未登录成功,退出运行 --" + driver.getCurrentUrl());
					break;
				}
			}
			LOG.info("登录成功--" + driver.getCurrentUrl());
			cookieSet = driver.manage().getCookies();
			for (Cookie ck : cookieSet) {
				LOG.debug(ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null) {
				driver.quit();
			}
		}
		return cookieSet;
	}

}
